<template>
  <el-dialog v-if="load" :title="title" v-model="visible" align-center width="580px" @close="handleClose" :close-on-click-modal="false">
    <el-form :model="formData" label-width="120px" :rules="rules" inline ref="ruleFormRef" class="formw200">
      <el-form-item label="VAT设置类型:" prop="vat_type" class="h-[32px]">
        <el-radio-group v-model="formData.vat_type" @change="changeVat">
          <el-radio :label="item.value" v-for="(item, index) in vat_type" :key="index">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="平台:" prop="platform_id">
        <el-select v-model="formData.platform_id" class="input" collapse-tags placeholder="平台" @change="changePlatform">
          <el-option v-for="(d, i) in platformList" :key="i" :label="d.platform_name" :value="d.platform_id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="站点:">
        <el-select v-model="formData.site" multiple class="input" collapse-tags clearable placeholder="站点" @change="changeSite">
          <el-option v-for="(d, i) in siteList" :key="i" :label="d.site_abbrev" :value="d.site_id"></el-option>
        </el-select>
        <el-button type="primary" class="ml-4" @click="checkAllSite">全选</el-button>
      </el-form-item>
      <el-form-item label="店铺:">
        <el-select v-model="formData.shop_id" class="input" multiple collapse-tags clearable placeholder="店铺">
          <el-option v-for="(d, i) in shopList" :key="i" :label="d.shop_name" :value="d.shop_id"></el-option>
        </el-select>
        <el-button type="primary" class="ml-4" @click="checkAllShop">全选</el-button>
      </el-form-item>

      <el-form-item label="发货国家:" prop="shipping_country">
        <SelectCountry v-model="formData.shipping_country" class="input" multiple placeholder="发货国家" :collapseTags="true" labelKey2="true"></SelectCountry>
      </el-form-item>
      <el-form-item label="到达国家:" prop="destination_country">
        <SelectCountry v-model="formData.destination_country" multiple class="input" placeholder="到达国家" :collapseTags="true" labelKey2="true"></SelectCountry>
      </el-form-item>

      <el-form-item label="州/省:">
        <el-input v-model="formData.province" :rows="5" type="textarea" class="input" placeholder="一行一个，按回车换行" />
      </el-form-item>
      <el-form-item label="运输方式:" v-if="formData.vat_type == 1">
        <SelectShippingMethod placeholder="运输方式" v-model="formData.logistic_id" multiple collapseTags style="width: 300px" />
      </el-form-item>
      <el-form-item label="税率:" prop="tax_rate">
        <el-input type="number" v-model="formData.tax_rate" placeholder="税率" class="input">
          <template #append>%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="计算公式:" prop="minimum_commission">
        <el-select v-model="formData.formula" class="input" collapse-tags clearable placeholder="计算公式">
          <el-option v-for="(d, i) in formula" :key="i" :label="d.label" :value="d.value"></el-option>
        </el-select>
        <el-tooltip class="box-item" effect="dark" placement="top">
          <template #content> 平台返回的订单金额不含税费：订单税费 = 订单金额 * 税率<br />平台返回的订单金额包含税费：订单税费 = 订单金额 / (1+税率) * 税率</template>
          <svg-icon icon-class="hint_line" class="ml-2" />
        </el-tooltip>
      </el-form-item>
      <el-form-item label="状态:" prop="additional_commission">
        <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" inline-prompt active-text="启用" inactive-text="禁用"></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, toRefs } from "vue"
import { detail, createSetting, updateSetting } from "../api"
import { ElMessage } from "element-plus"
import { tmsOverallOptions, getPlatformOptions, getSiteOptions, getShopOptions } from "@/api/public"
import SelectCountry from "@/components/Selects/SelectCountry"
import SelectShippingMethod from "@/components/Selects/SelectShippingMethod/index.vue"
const ruleFormRef = ref()
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
// 声明接收参数
const props = defineProps({
  title: {
    type: String,
    default: "新增",
  },
  ruleTypeOption: {
    type: Object,
    default: [],
  },
  formula: {
    type: Array,
    default: [],
  },
  vat_type: {
    type: Array,
    default: [],
  },
})
const data = reactive({
  formData: {
    platform_id: "",
    vat_type: 1,
    status: 0,
  },
  isType: false,
  platformList: [],
  siteList: [],
  shopList: [],
})
const { formData, isType, platformList, siteList, shopList } = toRefs(data)

const { title, ruleTypeOption, formula, vat_type } = toRefs(props)
const emit = defineEmits(["close", "confirm"])
const rules = reactive({
  vat_type: [
    {
      required: true,
      message: "必选",
      trigger: "change",
    },
  ],
  platform_id: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  tax_rate: [
    {
      required: true,
      message: "不能为空",
      trigger: "blur",
    },
  ],
  shipping_country: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  destination_country: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
})

// 打开弹窗
const open = (row = {}) => {
  if (!load.value) {
    load.value = true
  }
  if (row.id) {
    isType.value = true
    detail({ id: row.id }).then((res) => {
      loadings = reactive({})
      visible.value = true
      getSite(res.data.platform_id)
      getShop(res.data.platform_id, res.data.site)
      res.data.province = res.data.province?.join("\n")
      formData.value = res.data
    })
  } else {
    formData.value.vat_type = 2
    formData.value.formula = 2

    loadings = reactive({})
    isType.value = false
    visible.value = true
  }
}
// 关闭弹窗
const close = () => {
  formData.value = {}
  ruleFormRef.value.resetFields()
  visible.value = false
}

const handleClose = () => {
  close()
  emit("close")
}
// 提交
const submit = () => {
  let { validate } = ruleFormRef.value
  validate((valid) => {
    if (valid) {
      loadings.submit = true
      let { id, platform_id, site, shop_id, status, formula, vat_type, tax_rate, logistic_id, province, destination_country, shipping_country } = formData.value
      province = province?.split("\n")?.filter((v) => !!v.trim())
      province = province?.map((v) => v.trim())

      if (isType.value) {
        updateSetting({ id, platform_id, site, shop_id, status, formula, vat_type, tax_rate, logistic_id, province, destination_country, shipping_country })
          .then((res) => {
            ElMessage({ message: "保存成功", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      } else {
        createSetting({ platform_id, site, shop_id, status, formula, vat_type, tax_rate, logistic_id, province, destination_country, shipping_country })
          .then((res) => {
            ElMessage({ message: "保存成功", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      }
    }
  })
}
defineExpose({ open })

// 切换VAT设置类型
const changeVat = () => {
  formData.value.logistic_id = ""
}

// 获取平台
const getPlatform = async () => {
  try {
    const res = await getPlatformOptions()
    platformList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

// 选择平台
const changePlatform = async (val) => {
  siteList.value = []
  shopList.value = []
  formData.value.site = ""
  formData.value.shop_id = ""
  getSite(val)
}

// 获取站点
const getSite = async (id) => {
  try {
    const res = await getSiteOptions({
      platform_ids: [id],
    })
    siteList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

// 选择站点
const changeSite = async (val) => {
  shopList.value = []
  formData.value.shop_id = ""
  getShop(formData.value.platform_id, val)
}

// 获取店铺列表
const getShop = async (platform_id, site_ids) => {
  try {
    const res = await getShopOptions({
      site_ids,
      platform_ids: [platform_id],
    })
    shopList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

// 全选站点
const checkAllSite = async () => {
  if (siteList.value.length == 0) {
    ElMessage.error("站点列表为空")
    return
  }
  const site_ids = siteList.value.map((i) => i.site_id)
  formData.value.site = site_ids
  getShop(formData.value.platform_id, site_ids)
}

// 全选店铺
const checkAllShop = async () => {
  if (shopList.value.length == 0) {
    ElMessage.error("店铺列表为空")
    return
  }
  const shop_ids = shopList.value.map((i) => i.shop_id)
  formData.value.shop_id = shop_ids
}
onMounted(() => {
  getPlatform()
})
</script>
<style lang="scss" scoped>
.formw200 {
  :deep(.input) {
    width: 300px;
  }
}
:deep(.el-radio.el-radio--large) {
  height: initial;
}
:deep(input::-webkit-outer-spin-button),
:deep(input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
}
:deep(.el-input__inner) {
  line-height: 1px !important;
}
</style>
